<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- type -->
      <el-input
        v-model="listQuery.type"
        placeholder="Type"
        style="width: 300px;margin-bottom: 10px;vertical-align: middle;"
        suffix-icon="el-icon-search"
        clearable
        @keyup.enter.native="handleFilter"
      />
      <!-- 搜索 按钮 -->
      <el-button
        v-waves
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >Search</el-button>
      <!-- 添加按钮 -->
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >Add</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="typeList"
      border
      fit
      style="width: 100%;"
    >
      <el-table-column
        label="ID"
        type="index"
        align="center"
        width="100"
      >
        <template slot-scope="{row}">
          <span>{{ row.index }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Date" align="center">
        <template slot-scope="{row}">
          <span>{{ row.timestamp | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="Type" align="center">
        <template slot-scope="{row}">
          <el-tag>{{ row.type }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="Actions"
        align="center"
        width="200"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">Edit</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">Delete</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getTypeList"
    />

    <!-- 弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="right"
        label-width="120px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item label="Type" prop="type">
          <el-input v-model="temp.type" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button
          type="primary"
          @click="dialogStatus==='create'? createData() : updateData()"
        >Confirm</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchTypeList,
  createATpye,
  editType,
  deleteType
} from '@/api/section'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'

export default {
  name: 'SectionListItemType',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      typeList: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        type: ''
      },
      temp: {
        type: '',
        timestamp: Date.now()
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getTypeList()
  },
  methods: {
    /* 获取 type list */
    getTypeList() {
      this.listLoading = true
      fetchTypeList(this.listQuery).then(res => {
        this.typeList = res.data.items.map((item, index) => ({
          ...item, index: this.listQuery.limit * (this.listQuery.page - 1) + (index + 1)
        }))
        this.total = res.data.total
        this.listLoading = false
      })
    },
    /* 检索 */
    handleFilter() {
      this.listQuery.page = 1
      this.getTypeList()
    },
    /* 重置 temp */
    resetTemp() {
      this.temp = {
        type: '',
        timestamp: Date.now()
      }
    },
    /* 打开 弹窗 (创建) */
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /* 创建 */
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createATpye(this.temp).then(res => {
            this.total++
            this.typeList.unshift({ ...res.data, index: this.total })
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    /* 打开 弹窗 (更新)) */
    handleUpdate(row) {
      this.temp = row
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    /* 更新 */
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editType(this.temp).then(res => {
            const index = this.typeList.findIndex(v => v.id === this.temp.id)
            this.typeList.splice(index, 1, res.data)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    /* 删除 */
    handleDelete(row, index) {
      this.typeList.splice(index, 1)
      deleteType({ id: row.id, count: this.total }).then(res => {
        // this.total = res.data.total;
        this.total--
        this.$notify({
          title: 'Success',
          message: 'Delete Successfully',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style scoped>
</style>
